<template>
  <a-drawer
    :visible="formVisible"
    :width="500"
    unmount-on-close
    :title="isEdit ? '编辑' : '新增'"
    @ok="submit"
    @cancel="close"
  >
    <div>
      <a-form
        ref="form"
        :model="user"
        :rules="rules"
        :label-col-props="{ span: 8 }"
        :wrapper-col-props="{ span: 16 }"
      >
        <a-form-item field="name" label="用户名" required>
          <a-input v-model="user.name" placeholder="请填写用户名" />
        </a-form-item>
        <a-form-item field="age" label="年龄" required>
          <a-input v-model="user.age" placeholder="请填写年龄" />
        </a-form-item>
      </a-form>
    </div>
  </a-drawer>
</template>

<script lang="ts" setup>
  import { FieldRule, Message } from '@arco-design/web-vue';
  import { ref, reactive, watch, computed } from 'vue';
  import { saveUserInfo, updateUserInfo } from '@/api/demo/user';
  import { useVisible } from '@/hooks/visible';

  const form = ref();

  const initData = reactive({
    id: '',
    name: '',
    age: '',
  });

  const rules: Record<string, FieldRule[]> = {
    name: [
      {
        type: 'string',
        required: true,
        message: '用户名不能为空',
      },
    ],
    age: [
      {
        type: 'number',
        required: true,
        message: '年龄不能为空',
      },
    ],
  };

  const props = defineProps({
    visible: {
      type: Boolean,
      default: false,
    },
    formData: {
      type: Object,
      default: () => {
        return {};
      },
    },
  });

  const emit = defineEmits<{
    (e: 'update:visible', v: boolean): void;
    (e: 'refresh'): void;
  }>();

  const user = ref(props.formData);

  const { formVisible, close } = useVisible(props, emit);

  // 判断是编辑还是新增
  const isEdit = computed(() => !!user.value.id);

  const submit = async () => {
    formVisible.value = true;
    const validate = await form.value.validate();
    if (!validate) {
      if (isEdit.value) {
        await updateUserInfo(user.value).then(() => {
          Message.success('修改成功');
        });
      } else {
        await saveUserInfo(user.value).then(() => {
          Message.success('添加成功');
        });
      }
      user.value = { ...initData };
      formVisible.value = false;
      emit('refresh');
    }
  };

  watch(
    () => props.formData,
    (val) => {
      user.value = val;
    }
  );
</script>
